const express = require('express');
const cors = require('./middlewares/cors');
const logRoutes = require('./routes/logRoutes');
const userLogRoutes = require('./routes/userLogRoutes');
const toolRoutes = require('./routes/toolRoutes');
const db = require('./config/database');

const app = express();
const port = 3000;

// 测试数据库连接
const testDatabaseConnection = async () => {
  try {
    const [rows] = await db.query('SELECT 1 as test');
    console.log('✅ 数据库连接成功');
    return true;
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
    return false;
  }
};

// 中间件设置
app.use(cors);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 路由
app.use('/api/logs', logRoutes);
app.use('/api/userlogs', userLogRoutes);
app.use('/api/tools', toolRoutes);

// 基本路由
app.get('/', (req, res) => {
  res.json({ 
    message: 'Express + MySQL 服务器运行正常！',
    endpoints: {
      logs: '/api/logs'
    }
  });
});

// 启动服务器
app.listen(port, async () => {
  console.log(`🚀 服务器运行在 http://localhost:${port}`);
  console.log(`📚 API 文档: http://localhost:${port}/api/logs`);
  
  // 测试数据库连接
  await testDatabaseConnection();
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('正在关闭服务器...');
  process.exit();
});
